<style scoped>
[v-cloak] {
  display: none;
}
.container {
  background-color: #f0f2f5;
  padding: 30px;
  min-height: calc(100vh - 84px);
}
.component-item{
  min-height: 100px;
}
</style>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.pan-thumb {
  position: inherit !important;
  background-color: #fff;
}

@media only screen and (min-height: 560px){
  .list-body {
      height: calc(100vh - 235px);
      overflow-x: auto;
  }
}

</style>

<template>
  <div v-cloak class="container">
    <el-row justify="space-between">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-row type="flex" justify="space-between">
            <el-col :span="4" class="text-left">
              <span>品牌墙</span>
            </el-col>
            <el-col :span="2" class="text-right">
              <el-tooltip class="item" effect="dark" content="添加品牌" placement="bottom-end">
                <el-button type="primary" icon="el-icon-plus" circle @click="newBrand"/>
              </el-tooltip>
            </el-col>
          </el-row>
        </div>
        <div style="margin-bottom:50px;">
          <el-col :xs="12" :sm="8" :md="6" :lg="4" class="text-left pr-10">
            <el-input v-model="keyword" placeholder="输入品牌名称查询" clearable/>
          </el-col>
        </div>
      </el-card>
    </el-row>

    <el-row class="text-center list-body mt-10">
      <el-col v-for="item in listData" :xs="8" :sm="6" :md="4" :key="item.brandId" class="mt-20">
        <div v-if="item.brandLogo" @click="operateBrand(item)">
          <pan-thumb :image="item.brandLogo" :error="errorLogo" width="100px" height="100px">
            {{ item.brandName }}
          </pan-thumb>
        </div>
        <div v-else @click="operateBrand(item)">
          <pan-thumb :image="defaultLogo" width="100px" height="100px">
            {{ item.brandName }}
          </pan-thumb>
        </div>
        <div style="min-height: 40px;">{{ item.brandName }}</div>
      </el-col>
    </el-row>
    <el-dialog :visible.sync="brandSetDialog" label="品牌信息" width="30%">
      <el-form ref="brandForm" :model="brand" :rules="rules" label-width="100px">
        <el-form-item label="品牌名称" prop="brandName">
          <el-row :gutter="10" type="flex" justify="space-between" algin="middle">
            <el-col :xs="12" :md="12">
              <el-input v-model.trim="brand.brandName" style="width: 178px;" placeholder="输入品牌名称" @change="changeBrandName()" />
            </el-col>
            <el-col :xs="12" :md="12" class="text-right">
              <el-button v-waves type="primary" @click="saveBrand('brandForm')">保存</el-button>
              <el-button v-waves v-show="brand.brandId" type="danger" @click="deleteBrand(brand)">删除</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item ref="logoItem" label="品牌logo">
          <el-upload
            ref="uploadImage"
            v-model="brand.brandLogo"
            :auto-upload="false"
            :show-file-list="false"
            :file-list="imageFileList"
            :on-change="logoChange"
            action="string"
            class="avatar-uploader">
            <img v-if="brand.brandLogo" :src="brand.brandLogo" :onerror="errorLogo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>.
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import PanThumb from '@/components/PanThumb'
import waves from '@/directive/waves/index.js' // 水波纹指令
// , saveBrand
import { listBrand, saveBrand, deleteBrand, checkBrandName } from '@/api/brand'
import logo from '@/assets/images/logo.png'

export default {
  name: 'BrandList',
  components: {
    PanThumb
  },
  directives: {
    waves
  },
  data() {
    var validateLogo = (rule, value, callback) => {
      if (value === '' || typeof value === 'undefined') {
        callback(new Error('请选择品牌logo'))
      } else {
        callback()
      }
    }
    return {
      demo: {
        title: ''
      },
      brand: {},
      keyword: '',
      brandList: [],
      listData: [],
      brandSetDialog: false,
      errorLogo: 'this.src="' + logo + '"',
      defaultLogo: logo,
      imageFileList: [],
      brandDuplication: false,
      rules: {
        brandName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        brandLogo: [
          { validator: validateLogo }
        ]
      }
    }
  },
  watch: {
    brandSetDialog(value) {
      if (value === false) {
        this.resetForm('brandForm')
        this.loadBrandList()
      }
    },
    keyword() {
      this.searchBrand()
    }
  },
  created() {
    var self = this
    self.loadBrandList()
  },
  methods: {
    loadBrandList() {
      var self = this
      var data = {}
      listBrand(data).then(
        response => {
          if (response.data.status === 'success') {
            self.brandList = response.data.data
            self.searchBrand()
          } else {
            self.$message({
              message: '品牌加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        self.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },
    searchBrand() {
      var self = this
      self.listData = self.brandList.filter(data => !self.keyword || data.brandName.toLowerCase().includes(self.keyword.toLowerCase()))
    },
    newBrand() {
      var self = this
      self.imageFileList = []
      self.brand = {}
      self.brandSetDialog = true
    },
    operateBrand(item) {
      var self = this
      if (item) {
        self.brand = item
        self.imageFileList = []
        self.brandSetDialog = true
      } else {
        self.$message({
          message: '修改数据为空,请刷新页面重试',
          type: 'warning'
        })
      }
    },
    changeBrandName() {
      var self = this
      if (!self.brand.brandName) {
        self.brandDuplication = false
        return
      }
      var data = { brandName: self.brand.brandName, brandId: self.brand.brandId }
      checkBrandName(data).then(
        response => {
          if (response.data.status === 'success') {
            if (response.data.data === true) {
              self.brandDuplication = true
            } else {
              self.brandDuplication = false
            }
          } else {
            self.brandDuplication = false
            self.$message({
              message: '检查品牌失败，' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        self.brandDuplication = false
        self.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },
    saveBrand(formName) {
      var self = this
      self.$refs[formName].validate((valid) => {
        if (valid) {
          self.$confirm('确认保存吗?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (self.brandDuplication === true) {
              self.$message({
                type: 'warning',
                message: '已有该品牌'
              })
              return
            }
            var fromData = new FormData()
            fromData.append('brandId', self.brand.brandId ? self.brand.brandId : '')
            fromData.append('brandName', self.brand.brandName ? self.brand.brandName : '')
            fromData.append('brandLogo', self.imageFileList[0] ? self.imageFileList[0].raw : '')
            saveBrand(fromData).then(response => {
              if (response.data.status === 'success') {
                self.loadBrandList()
                self.$message({
                  type: 'success',
                  message: '品类保存成功'
                })
                self.brandSetDialog = false
              } else {
                this.$message({
                  message: '品牌保存失败' + response.data.messge,
                  type: 'warning'
                })
              }
            }).catch(() => {
              self.$message({
                type: 'info',
                message: '网络请求失败'
              })
            })
          }).catch(() => {
            self.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
        } else {
          self.$message({
            type: 'warning',
            message: '必填项不能为空'
          })
          return false
        }
      })
    },
    deleteBrand() {
      var self = this
      if (!self.brand.brandId || typeof self.brand.brandId === 'undefined') {
        self.$message({
          type: 'warning',
          message: '品牌不存在！或者品牌已经删除！'
        })
      }
      self.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBrand(self.brand.brandId).then(response => {
          if (response.data.status === 'success') {
            self.loadBrandList()
            self.brandSetDialog = false
            self.resetForm('brandForm')
            self.$message({
              type: 'success',
              message: '品类删除成功'
            })
          } else {
            this.$message({
              message: '品牌删除失败' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
          self.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
      }).catch(() => {
        self.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    logoChange(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 1
      if (!isLt2M) {
        this.$refs.uploadImage.clearFiles()
        this.$message.error('上传头像图片大小不能超过 1M')
        return false
      }
      this.imageData = file.raw
      this.imageFileList = []
      this.imageFileList.push(file)
      if (file) {
        this.brand.brandLogo = URL.createObjectURL(file.raw)
        this.$refs['logoItem'].clearValidate()
      }
    }
  }
}
</script>
